package edu.mju.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.mju.eduservice.entity.CourseType;
import edu.mju.eduservice.service.CourseTypeService;
import edu.mju.eduservice.vo.coursetype.CourseTypeData;
import edu.mju.servicebase.exception.StuException;

/**
 * @Author:wyp
 * @Date:2020/8/30 17:52
 */
public class CourseTypeListener extends AnalysisEventListener<CourseTypeData> {

    public CourseTypeService courseTypeService ;

    public CourseTypeListener() {
    }

    public CourseTypeListener(CourseTypeService courseTypeService) {
        this.courseTypeService = courseTypeService;
    }

    /**
     *  一行一行读取excel文件
     * @param courseTypeData
     * @param analysisContext
     */
    @Override
    public void invoke(CourseTypeData courseTypeData, AnalysisContext analysisContext) {
        if(courseTypeData == null){
            throw new StuException(20001,"文件数据为空");
        }

        //判断一级分类是否重复
        CourseType oneOnly = this.isOneOnly(courseTypeService, courseTypeData.getOneTypeName());
        if(oneOnly == null){
            oneOnly = new CourseType();
            oneOnly.setParentId("0");
            oneOnly.setTypeName(courseTypeData.getOneTypeName());
            courseTypeService.save(oneOnly);
        }

        //判断二级分类是否重复
        CourseType twoOnly = this.isTwoOnly(courseTypeService, courseTypeData.getTwoTypeName(), oneOnly.getId());
        if(twoOnly == null){
            twoOnly = new CourseType();
            twoOnly.setParentId(oneOnly.getId());
            twoOnly.setTypeName(courseTypeData.getTwoTypeName());
            courseTypeService.save(twoOnly);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }



    /**
     *  判断一级分类是否重复
     * @param courseTypeService
     * @param typeName 类型名称
     * @return CourseType对象
     */
    private CourseType isOneOnly(CourseTypeService courseTypeService,String typeName){
        QueryWrapper<CourseType> wrapper = new QueryWrapper<>();
        wrapper.eq("type_name",typeName);
        wrapper.eq("parent_id","0");
        CourseType obj = courseTypeService.getOne(wrapper);
        return obj;
    }

    /**
     *  判断二级分类是否重复
     * @param courseTypeService
     * @param typeName 类型名称
     * @return CourseType对象
     */
    private CourseType isTwoOnly(CourseTypeService courseTypeService,String typeName,String parent_id){
        QueryWrapper<CourseType> wrapper = new QueryWrapper<>();
        wrapper.eq("type_name",typeName);
        wrapper.eq("parent_id",parent_id);
        CourseType obj = courseTypeService.getOne(wrapper);
        return obj;
    }
}
